package application3.controller;

import application2.contorller.Controller;
import application3.validator.ProductValidator;
import common.action.SaveProductAction;
import common.domain.Product;
import common.form.ProductForm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * 带有验证器的保存产品控制器
 */
public class SaveProductController implements Controller {
    public String handleRequest(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        // 1、获取前端传来的数据
        ProductForm productForm = new ProductForm();
        productForm.setName(request.getParameter("name"));
        productForm.setDescription(request.getParameter("description"));
        productForm.setPrice(request.getParameter("price"));

        // 2、 验证产品表单类
        ProductValidator productValidator = new ProductValidator();
        List<String> errors = productValidator.validate(productForm);
        if (errors.isEmpty()) {
            // 验证通过
            // 将Form Object 转化为Domain Object
            Product product = new Product();
            product.setName(productForm.getName());
            product.setDescription(productForm.getDescription());
            product.setPrice(Float.parseFloat(productForm.getPrice()));

            // 业务操作
            SaveProductAction saveProductAction = new SaveProductAction();
            saveProductAction.save(product);

            // 存储HttpSession中
            request.setAttribute("product", product);

            // 页面跳转
            return "/WEB-INF/application3/jsp/ProductDetail3.jsp";
        } else {
            // 验证失败
            // 返回前台错误信息，并且返回原始表格数据
            request.setAttribute("errors", errors);
            request.setAttribute("form", productForm);
            // 页面跳转
            return "/WEB-INF/application3/jsp/ProductForm3.jsp";
        }


    }
}
